package com.serv.merchant;

import java.util.Date;

import com.jfinal.aop.Inject;
import com.jfinal.kit.HashKit;
import com.serv.common.base.BaseController;
import com.serv.common.model.Employee;
import com.serv.common.model.Merchant;
import com.serv.common.model.sys.Organization;
import com.serv.common.model.sys.User;
import com.serv.common.service.MerchantService;
import com.serv.common.service.sys.OrganizationService;
import com.serv.common.service.sys.UserService;
import com.serv.util.AjaxObject;

public class MerchantController extends BaseController {
	@Inject
	MerchantService merchService;
	
	@Inject
	OrganizationService orgService;
	
	@Inject
	UserService userService;
	
	public void index() {
		render("index.html");
	}
	
	public void add(){
		render("add.html");
	}
	
	public void create(Merchant merchant,Employee employee,User user){
		String id = orgService.getRoot().nextId();
		new Organization().set("id",id).set("name",merchant.get("name")).save();
		
		Date now = new Date();
		merchant.set("id",id).set("status",1).set("created_at",now).set("updated_at",now).save();
		
		String salt = HashKit.generateSalt(32);
		String encrypt = userService.encrypt(user.getStr("password"),salt);
		String userId = userService.uuid();
		user.set("id",userId)
			.set("realname",employee.get("realname"))
			.set("password",encrypt)
			.set("salt",salt)
			.set("status",1)
			.set("organization_id",id)
			.set("created_at",now);
		user.save();
		employee.set("id",userId).set("merchant_id",id)
			.set("status",1).set("created_at",now).set("updated_at",now);
		employee.save();
		
		renderJson(AjaxObject.newOk("成功成功"));
	}
}
